package com.atguigu.flink.chapter08;


import com.atguigu.flink.bean.LoginEvent;
import com.atguigu.flink.util.AtguiguUtil;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.windows.GlobalWindow;
import org.apache.flink.util.Collector;

import java.util.List;

/**
 * @Author lzc
 * @Date 2022/9/8 9:02
 */
public class Flink05_High_Project_Login {
    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 2000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        env
            .readTextFile("input/LoginLog.csv")
            .map(new MapFunction<String, LoginEvent>() {
                @Override
                public LoginEvent map(String line) throws Exception {
                    String[] data = line.split(",");
                    return new LoginEvent(
                        Long.valueOf(data[0]),
                        data[1],
                        data[2],
                        Long.parseLong(data[3]) * 1000  // 把s变成ms
                    );
                }
            })
            .keyBy(LoginEvent::getUserId)
            .countWindow(2, 1)
            .process(new ProcessWindowFunction<LoginEvent, String, Long, GlobalWindow>() {
                @Override
                public void process(Long userId,
                                    Context ctx,
                                    Iterable<LoginEvent> elements,
                                    Collector<String> out) throws Exception {
                
                    // 窗口内的元素个数最多两个
                    List<LoginEvent> list = AtguiguUtil.toList(elements);
                    if (list.size() == 2) {
                        LoginEvent e1 = list.get(0);
                        LoginEvent e2 = list.get(1);
    
                        String eventType1 = e1.getEventType();
                        String eventType2 = e2.getEventType();
    
                        Long eventTime1 = e1.getEventTime();
                        Long eventTime2 = e2.getEventTime();
    
    
                        if ("fail".equals(eventType1) && "fail".equals(eventType2) && Math.abs(eventTime1 - eventTime2) <= 2000) {
                            out.collect("用户:" + userId + " 正在恶意登录");
                        }
                    }
                }
            })
            .print();
        
        
        env.execute();
    }
}
